package org.sky.component.msg.mail.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.internet.MimeMessage;

import org.sky.component.msg.mail.bean.MailInfo;
import org.sky.component.msg.mail.service.IMailService;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;


/**
 * 邮件发送管理类；实现邮件的发送
 * 
 * @version 1.0
 */
public class MailServiceImpl implements IMailService{
	
	private JavaMailSenderImpl mailSender;

	
	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	public MailInfo sendTextMail(MailInfo mailInfo) {
		int startTime = 0;
		int endTime = 0;
		startTime = Integer.parseInt(new SimpleDateFormat("mmssSSS")
				.format(new Date()));
		MimeMessage mail = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(mail,"UTF-8");  
			helper.setTo(mailInfo.getReceiver());// 接受者
			helper.setFrom(mailSender.getUsername());// 发送者
			helper.setSubject(mailInfo.getSubject());// 主题
			helper.setText(mailInfo.getContent(),true);// 邮件内容
			mailSender.send(mail);
			mailInfo.setIsSuccess("1");
		} catch (Exception e) {
			// 失败原因
			mailInfo.setFailure(e.getMessage());
			// 失败标志
			mailInfo.setIsSuccess("0");
		}
		endTime = Integer.parseInt(new SimpleDateFormat("mmssSSS")
				.format(new Date()));
		mailInfo.setUseTime(String.valueOf(endTime - startTime));
		System.out.println(mailInfo.getIsSuccess());
		System.out.println(mailInfo.getFailure());
		return mailInfo;
	}

}